<template>
  <div class="myvideo" :class="videoIsFull ? 'full' : ''">
    <video 
      class="myvideo_video" 
      id="player-container-id" 
      ref="myVideo" 
      preload="auto" 
      playsinline 
      webkit-playsinline 
      x5-playsinline 
      :currentTime="videoSetTime" 
      :controls="true"
      @play="playFn" 
      @pause="pauseFn" 
      @ended="endedFn" 
      @timeupdate="timeupdateFn"
      @loadedmetadata="loadedmetadataFn"
    ></video>
    <!-- <div class="myvideo_controls">
      <div class="myvideo_controls_button">
        <div class="myvideo_controls_button_left">
          <span class="iconfont icon-PauseCircle" @click="pauseClickFn" v-if="videoIsPlay"></span>
          <span class="iconfont icon-PlayCircle" @click="playClickFn" v-else></span>
          <span class="timing">{{ videoStartTime }} / {{ videoEndTime }}</span>
        </div>
        <div class="myvideo_controls_button_right">
          <div class="volume">
            <span class="iconfont icon-SpeakerHigh icon-volume" @click="voiceClickFn" v-if="videoIsVolume"></span>
            <span class="iconfont icon-SpeakerX icon-volume" @click="muteClickFn" v-else></span>
            <div class="volume_slider">
              <el-slider v-model="videoVolume" height="100px" :show-tooltip="false" vertical
                @change="videoVolumeChangeFn" />
            </div>
          </div>
          <span style="width: 10px"></span>
          <div class="dropdown">
            <span class="dropdown_name">{{ videoYuanName }}</span>
            <ul class="dropdown_ul">
              <li class="dropdown_ul_li" v-for="(item, index) in videoYuan" :key="index">
                <a class="dropdown_ul_li_a" :href="`/curriculum_details/${courseId}-${chapterId}-${videoId}.html?y=${item}`">{{ item == 100040 ? '高清' : item == 100030 ? '流畅' : '原画' }}</a>
              </li>
            </ul>
          </div>
          <span style="width: 18px"></span>
          <span class="iconfont icon-CornersIn" @click="outFullClickFn" v-if="videoIsFull"></span>
          <span class="iconfont icon-CornersOut" @click="fullClickFn" v-else></span>
        </div>
      </div>
      <div style="padding: 0 5px">
        <div ref="container" class="myvideo_controls_slider" @mousedown.stop="startDrag">
          <div class="myvideo_controls_slider_select" :style="{ width: sliderValue + '%' }">
            <span class="myvideo_controls_slider_select_spot"></span>
          </div>
        </div>
      </div>
    </div> -->
  </div>
  <!-- 系统提示 -->
  <!-- <el-dialog v-model="dialogVisible" title="系统提示" width="500" :close-on-click-modal="false"
    :close-on-press-escape="false" :show-close="false">
    <span>系统检测到您在{{ dialogSetTime }}s内未有任何操作，被视为学员未在屏幕前观看学习！</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogConfirmFn">我已知晓</el-button>
      </div>
    </template>
  </el-dialog> -->
</template>

<script setup>
import { enterFullScreen, exitFullScreen, convertSecondsToHMS } from "~/utils/utils";
import { updateProgressApi } from "~/server/api";
import 'tcplayer.js/dist/tcplayer.min.css';
useHead({
  script: [
    { type: 'text/javascript', src: 'https://vod-tool.vod-qcloud.com/dist/static/js/tcplayer.v4.9.1.min.js' }
  ]
})
const props = defineProps(['videoCurrentData', 'videoYuan', 'videoYuanName', 'videoSign'])
const courseId = useRoute().params.courseId;
const chapterId = useRoute().params.chapterId;
const videoId = useRoute().params.videoId;
const currentVideoData = ref(props.videoCurrentData); // 当前视频数据
const myVideo = ref(null); // 视频ref属性
const videoIsPlay = ref(false); // 视频播放按钮 true 播放 false 暂停
const videoIsFull = ref(false); // 全屏按钮 true 满屏 false 半屏
const videoIsVolume = ref(true); // 音量按钮 true 有声 false 无声
const videoStartTime = ref("00:00"); // 视频计时 时分秒
const videoEndTime = ref("00:00"); // 视频总时长 时分秒
const videoSetTime = ref(0); // 设置视频时间 秒
const videoTimeLog = ref(0); // 视频时间日志 秒
const videoDuration = ref(0); // 视频总时长 秒
const videoVolume = ref(100); // 视频声音初始音量最大 0-100
const container = ref(null); // 滑块ref属性
const dragging = ref(false); // 滑块标识
const sliderValue = ref(0); // 滑块值 百分比
const _sliderValue = ref(0); // 滑块值 原型
const sliderMoveToTime = ref(0); // 滑块移动转时间 秒
const classHoursTimer = ref(null); // 学时 计时器
const dialogVisible = ref(false); // 弹窗标识
const dialogSetTime = ref(60 * 10); // 间隔多少秒开启弹窗
const dialogTimer = ref(null); // 未有任何操作弹窗 计时器
const mouseMoveLastTime = ref(0); // 记录鼠标移动的时间
const emit = defineEmits(['end']);
// 加载视频
function initVideoFn() {
  TCPlayer('player-container-id', { // player-container-id 为播放器容器ID，必须与html中一致
    fileID: currentVideoData.value.video, // 请传入需要播放的视频fileID 必须
    appID: useRoute().meta.video_appId, // 请传入点播账号的子应用appID 必须
    controls: true,
    psign: props.videoSign, // 请传入播放器签名psign 必须
    autoplay: false // 是否自动播放
  })
}
// 视频播放触发
function playFn() {
  videoIsPlay.value = true;
  // 未学完
  if (useRoute().meta.userinfo && currentVideoData.value.clock.status == 2) {
    // 学时计时器
    classHoursTimer.value = setInterval(() => {
      updateLearningRecords();
    }, 2000);
    // 未有任何操作弹窗计时器
    // dialogTimer.value = setInterval(() => {
    //   let currentTime = new Date().getTime();
    //   let countTime = parseInt((currentTime - mouseMoveLastTime.value) / 1000);
    //   if (countTime >= dialogSetTime.value) {
    //     myVideo.value.pause()
    //     if (videoIsFull.value) {
    //       exitFullScreen()
    //       videoIsFull.value = false;
    //     }
    //     dialogVisible.value = true;
    //   }
    // }, 5000);
  }
}
// 视频暂停触发
function pauseFn() {
  videoIsPlay.value = false;
  clearTimer();
  // 未学完 记录学时
  if (useRoute().meta.userinfo && currentVideoData.value.clock.status == 2) {
    updateLearningRecords();
  }
}
// 视频结束触发
function endedFn() {
  videoIsPlay.value = false;
  clearTimer();
  outFullClickFn();
  if (useRoute().meta.userinfo) {
    emit('end')
    updateLearningRecords();
  }
}
// 视频播放监听
function timeupdateFn(e) {
  videoTimeLog.value = e.target.currentTime;
  videoStartTime.value = convertSecondsToHMS(e.target.currentTime);
  if (!dragging.value) {
    sliderValue.value = (e.target.currentTime / videoDuration.value) * 100;
  }
}
// 视频加载触发
function loadedmetadataFn(e) {
  // 获取视频总时长
  if (e.target.duration) {
    videoEndTime.value = convertSecondsToHMS(e.target.duration);
    videoDuration.value = e.target.duration;
    // 未学完 重新设定视频开始时间 滑块位置
    if (useRoute().meta.userinfo && currentVideoData.value.clock.status == 2) {
      videoSetTime.value = currentVideoData.value.clock.currentDuration;
      sliderMoveToTime.value = currentVideoData.value.clock.currentDuration;
    }
  }
}
// 视频音量改变触发
function videoVolumeChangeFn(val) {
  videoIsVolume.value = val > 0 ? true : false;
  videoVolume.value = val;
  myVideo.value.volume = parseFloat((val / 100).toFixed(1));
}
// 点击视频播放
function playClickFn() {
  myVideo.value.play();
}
// 点击视频暂停
function pauseClickFn() {
  myVideo.value.pause();
}
// 点击静音
function voiceClickFn() {
  videoIsVolume.value = false;
  videoVolume.value = 0;
  myVideo.value.volume = 0;
}
// 点击取消静音
function muteClickFn() {
  videoIsVolume.value = true;
  videoVolume.value = 100;
  myVideo.value.volume = 1;
}
// 点击全屏
function fullClickFn() {
  if (!videoIsFull.value) {
    videoIsFull.value = true;
    enterFullScreen();
  }
}
// 点击退出全屏
function outFullClickFn() {
  if (videoIsFull.value) {
    videoIsFull.value = false;
    exitFullScreen();
  }
}
// 鼠标按下
function startDrag(e) {
  dragging.value = true;
  countSlider(e);
  document.addEventListener("mousemove", videoControlsMouseMove);
}
// 计算滑块在容器中的位置 百分比 时间
function countSlider(e) {
  // 得出百分比
  let containerWidth = container.value.offsetWidth;
  let mouseX = e.clientX - container.value.getBoundingClientRect().left;
  let _percentage = ((mouseX / containerWidth) * 100).toFixed(6);
  _sliderValue.value = _percentage <= 0 ? 0 : _percentage > 100 ? 100 : parseFloat(_percentage);
  // 换算时间
  sliderMoveToTime.value = parseFloat(((_sliderValue.value / 100) * videoDuration.value).toFixed(6));
  if (useRoute().meta.userinfo) {
    // 已学完 随便滑动
    if (currentVideoData.value.hours === 0 || currentVideoData.value.clock.status > 2) {
      sliderValue.value = _sliderValue.value;
    } else {
      // 未学完 滑块只能后退不能前进
      if (sliderMoveToTime.value < videoTimeLog.value) {
        sliderValue.value = _sliderValue.value;
      }
    }
  } else {
    sliderValue.value = _sliderValue.value;
  }
}
// 鼠标抬起
function endDrag() {
  dragging.value = false;
  if (useRoute().meta.userinfo) {
    // 已学完
    if (currentVideoData.value.hours === 0 || currentVideoData.value.clock.status > 2) {
      videoSetTime.value = sliderMoveToTime.value;
    } else {
      // 未学完 视频只能后退不能前进
      if (sliderMoveToTime.value < videoTimeLog.value) {
        videoSetTime.value = sliderMoveToTime.value;
      }
    }
  } else {
    videoSetTime.value = sliderMoveToTime.value;
  }
  document.removeEventListener("mousemove", videoControlsMouseMove);
  // videoControlsHideFn()
}
// 更新学习记录
function updateLearningRecords() {
  useServerRequest(updateProgressApi, {
    method: "post",
    body: JSON.stringify({
      courseVideoId: currentVideoData.value.id || "",
      currentDuration: videoTimeLog.value || 0,
    }),
  }).then(({ errno, errmsg, result }) => {
    if (errno !== 0) {
      ElMessage.error(errmsg);
      myVideo.value.pause()
      return false;
    }
  }).catch((err) => {
    myVideo.value.pause()
  });
}
// 我已知晓
function dialogConfirmFn() {
  dialogVisible.value = false;
  myVideo.value.play();
}
// 切换窗口触发
function pageLeaving() {
  if (document.visibilityState == "hidden" && videoIsPlay.value) {
    myVideo.value.pause();
  }
}
// 视频控件鼠标移动
function videoControlsMouseMove(event) {
  if (dragging.value) {
    let rec = myVideo.value.getBoundingClientRect()
    // let startX = rec.x + 15;
    // let endX = rec.x + rec.width - 15;
    let startX = rec.x + 10;
    let endX = rec.x + rec.width - 10;
    let moveX = event.x;
    if (moveX >= startX && moveX <= endX) {
      let moveNowX = moveX - startX;
      // let rightWidth = (rec.width - 30) - moveNowX;
      // let leftWidth = (rec.width - 30) - rightWidth;
      let rightWidth = (rec.width - 20) - moveNowX;
      let leftWidth = (rec.width - 20) - rightWidth;
      countSlider({ clientX: moveX })
    }
  }
}
// 记录鼠标在页面移动的时间
function pageMouseMove(event) {
  mouseMoveLastTime.value = new Date().getTime();
}
// 页面滚动条
function pageScroll() {
  if (window.scrollY >= 640 && videoIsPlay.value) {
    myVideo.value.pause();
  }
}
// 清除所有计时器
function clearTimer() {
  clearInterval(classHoursTimer.value);
  classHoursTimer.value = null;
  clearInterval(dialogTimer.value);
  dialogTimer.value = null;
}
/**
 * 页面挂载
 */
onMounted(() => {
  setTimeout(() => {
    initVideoFn()
  }, 500)
  // 获取视频总时长
  if (myVideo._value.duration && videoEndTime.value == "00:00") {
    videoEndTime.value = convertSecondsToHMS(myVideo._value.duration);
    videoDuration.value = myVideo._value.duration;
    // 未学完 重新设定视频开始时间 滑块位置
    if (useRoute().meta.userinfo && currentVideoData.value.clock.status == 2) {
      videoSetTime.value = currentVideoData.value.clock.currentDuration;
      sliderMoveToTime.value = currentVideoData.value.clock.currentDuration;
    }
  }
  // 监听页面鼠标抬起
  document.addEventListener("mouseup", endDrag);
  if (useRoute().meta.userinfo) {
    // 切换窗口视频暂停
    document.addEventListener("visibilitychange", pageLeaving);
    // 监听页面鼠标移动
    document.addEventListener("mousemove", pageMouseMove);
    // 监听页面滚动条
    document.addEventListener("scroll", pageScroll);
  }
});
/**
 * 页面更新
 */
onUpdated(() => {
  // 签到后更新视频数据
  currentVideoData.value = props.videoCurrentData;
});
/**
 * 页面销毁
 */
onUnmounted(() => {
  document.removeEventListener("mouseup", endDrag);
  if (useRoute().meta.userinfo) {
    document.removeEventListener("visibilitychange", pageLeaving);
    document.removeEventListener("mousemove", pageMouseMove);
    document.removeEventListener("scroll", pageScroll);
    clearTimer();
  }
});
</script>

<style lang="less" scoped>
@import "~/assets/iconfont/iconfont.css";

* {
  user-select: none;
  outline: none;
}

.myvideo {
  background-color: #000;
  position: relative;
  overflow: hidden;

  &_video {
    width: 100%;
    height: 100%;
    min-height: 410px;
    display: block;
  }

  &_controls {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 10;
    background: linear-gradient(transparent, #000);
    padding: 10px 10px 0 10px;
    opacity: .2;
    transition: all .3s;

    &:hover {
      opacity: 1;
      transition: all .3s;
    }

    &_button {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #fff;

      &_left {
        display: flex;
        align-items: center;

        .iconfont {
          font-size: 34px;
          cursor: pointer;
        }

        .timing {
          margin-top: 5px;
          margin-left: 10px;
          font-size: 14px;
          line-height: 14px;
        }
      }

      &_right {
        display: flex;
        align-items: center;
        padding-right: 5px;

        .dropdown {
          position: relative;

          &_name {
            font-size: 15px;
            line-height: 22px;
            color: #fff;
          }

          &_ul {
            position: absolute;
            left: 50%;
            bottom: 100%;
            z-index: 1;
            transform: translateX(-50%);
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.02);
            padding: 2px 0;
            display: none;

            &_li {
              border-bottom: 1px solid #e6e6e6;

              &_a {
                font-size: 13px;
                padding: 7px 15px;
                display: block;
                white-space: nowrap;

                &:hover {
                  background-color: #ebedf0;
                  color: #409eff;
                }
              }

              &:last-child {
                border-bottom: 0;
              }
            }
          }

          &:hover {
            .dropdown_ul {
              display: block;
            }
          }
        }

        .iconfont {
          font-size: 24px;
          cursor: pointer;

          &.icon-volume {
            padding: 0 10px;
            font-size: 22px;
          }
        }

        .volume {
          position: relative;

          &_slider {
            position: absolute;
            bottom: 100%;
            left: 0;
            z-index: 1;
            width: 42px;
            padding: 20px 0 15px 0;
            border-radius: 22px 22px 0 0;
            background-color: rgba(0, 0, 0, .5);
            display: none;
            align-items: center;
            justify-content: center;
          }

          &:hover {
            background-color: rgba(0, 0, 0, .5);
            border-radius: 0 0 24px 24px;

            .volume_slider {
              display: flex;
            }
          }
        }
      }
    }

    &_slider {
      height: 32px;
      position: relative;

      &::before {
        content: "";
        position: absolute;
        top: 10px;
        right: 0;
        left: 0;
        height: 8px;
        border-radius: 8px;
        background-color: rgba(255, 255, 255, 0.5);
      }

      &_select {
        width: 0%;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        z-index: 2;

        &::before {
          content: "";
          position: absolute;
          top: 10px;
          right: 0;
          left: 0;
          height: 8px;
          border-radius: 8px;
          // background-color: #ff3f29;
          background-color: #409eff;
        }

        &_spot {
          display: block;
          width: 18px;
          height: 18px;
          border-radius: 10px;
          background-color: #fff;
          position: absolute;
          top: 5px;
          left: calc(100% - 7px);
          z-index: 99;
          cursor: pointer;

          &:hover {
            box-shadow: 0 0 5px #fff;
          }
        }
      }
    }
  }

  &.full {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9999;
  }
}

/* 全屏按钮 */
video::-webkit-media-controls-fullscreen-button {
  display: none !important;
}

/* 播放按钮 */
video::-webkit-media-controls-play-button {
  display: none !important;
}

/* 进度条 */
video::-webkit-media-controls-timeline {
  display: none !important;
}

/* 观看的当前时间 */
video::-webkit-media-controls-current-time-display {
  display: none !important;
}

/* 剩余时间 */
video::-webkit-media-controls-time-remaining-display {
  display: none !important;
}

/* 音量按钮 */
video::-webkit-media-controls-mute-button {
  display: none !important;
}

video::-webkit-media-controls-toggle-closed-captions-button {
  display: none !important;
}

/* 音量的控制条 */
video::-webkit-media-controls-volume-slider {
  display: none !important;
}

/* 所有控件 */
video::-webkit-media-controls-enclosure {
  display: none !important;
}

/* 设置视频播放中的背景 */
video::-webkit-media-text-track-background {
  background-color: #000;
}
</style>